package com.andrewchatham.pony;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

class DB {
	private DatabaseHelper mHelper;
	private final String mTable;
	protected Context mContext;
	protected SQLiteDatabase mDB;

	public DB(Context context, String table, int version, String create) {
		mContext = context;
		mTable = table;
		mHelper = new DatabaseHelper(context, table, version, create);
	}

	class DatabaseHelper extends SQLiteOpenHelper {
		private final String mCreate;
		private final String mTable;
		private final static String TAG = "DB";

		DatabaseHelper(Context context, String name, int version, String create)  {
			super(context, name, null, version);
			mCreate = create;
			mTable = name;
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.d(TAG, "Create db");
			db.execSQL(mCreate);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, 
				int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion 
					+ " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + mTable);
			onCreate(db);
		}
	}


	public DB open() throws SQLException {
		mDB = mHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mHelper.close();
	}

	public void clear() {
		mDB.delete(mTable, null, null);
	}

}